package utils;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public abstract class AbstractBean<M> {
		private Class<M> entityClass;
		
		public AbstractBean(Class<M> entityClass){
			this.entityClass = entityClass;
		}
		
		protected abstract EntityManager getEntityManager();
		
		public void create(M entity){
			getEntityManager().persist(entity);
		}
		
		public void edit(M entity){
			getEntityManager().merge(entity);
		}
		 public M find(Object id) {
		        return getEntityManager().find(entityClass, id);
		    }
		public void remove(M entity){
			getEntityManager().remove(getEntityManager().merge(entity));
		}
		public List<M> find(){
			return ((TypedQuery<M>)getEntityManager().createNamedQuery(entityClass.getSimpleName() + ".find", entityClass)).getResultList();
			
		}
		
		public List<M> findAll(){
			return ((TypedQuery<M>)getEntityManager().createNamedQuery(entityClass.getSimpleName() + ".findAll", entityClass)).getResultList();
			
		}
		public List<M> findRange(int min, int max){
			TypedQuery<M> range = getEntityManager().createNamedQuery(entityClass.getSimpleName() + ".findAll", entityClass);
			range.setMaxResults(max - min);
			range.setFirstResult(min);
			return range.getResultList();
		}
		/*
		public int count(){
			CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
			Root<M> root = cq.from(entityClass);
			cq.select(getEntityManager().getCriteriaBuilder().count(root));
			Query q = getEntityManager().createQuery(cq);
			return ((Long) q.getSingleResult()).intValue();
		}
		 */
		
}
